package cn.wipace.actionlib.util;

import android.content.Context;

import java.lang.reflect.Field;

/**
 * Created by Administrator on 2017/5/5.
 */

public class UserActionUtil {

    public static int getResourceIdByName(String packageName, String className, String name) {

        Class r = null;
        int id = 0;
        try {
            r = Class.forName(packageName + ".R");
            Class[] classes = r.getClasses();
            Class desireClass = null;
            for (int i = 0; i < classes.length; i++) {
                if (classes[i].getName().split("\\$")[1].equals(className)) {
                    desireClass = classes[i];
                    break;
                }
            }
            if (desireClass != null)
                id = desireClass.getField(name).getInt(desireClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return id;
    }

    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

    private static Object getResourceId(Context context,String name, String type) {

        String className = context.getPackageName() +".R";

        try {

            Class cls = Class.forName(className);

            for (Class childClass : cls.getClasses()) {

                String simple = childClass.getSimpleName();

                if (simple.equals(type)) {
                    for (Field field : childClass.getFields()) {
                        String fieldName = field.getName();
                        if (fieldName.equals(name)) {
                            System.out.println(fieldName);
                            return field.get(null);
                        }
                    }
                }
            }

        } catch (Exception e) {

            e.printStackTrace();

        }

        return null;

    }

    /**

     *context.getResources().getIdentifier无法获取到styleable的数据

     * @paramcontext

     * @param name

     * @return

     */

    public static int getStyleable(Context context, String name) {

        return ((Integer)getResourceId(context, name,"styleable")).intValue();

    }
}
